package com.jinglvhuanjing.app.utils;


import com.aill.androidserialport.SerialPort;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

//饿汉模式：（线程安全）
public class SingletonSerl_Old {


    private  static SerialPort serialPort = null;
    // 静态私有成员变量
    private static SingletonSerl_Old instance = new SingletonSerl_Old();
    // 私有构造函数
    private SingletonSerl_Old() {
    }
    // 静态公有工厂方法，判断成员变量是否为空，不为空则实例化
    public static SingletonSerl_Old getInstance() throws IOException {

        return instance;
    }


    /**
     * 获取串口连接对象
     * @return
     */
    public   SerialPort getSerialPortConnect(){
        try {
            if(serialPort==null){
                SerialPort.setSuPath("/system/xbin/su");
                //默认su路径是/system/bin/su，有些设备su路径是/system/xbin/su
                //在new SerialPort();之前设置su路径
                serialPort = new SerialPort(new File("/dev/ttyS1"), 9600, 0);
            }
        }catch (Exception e){
            try {
                SerialPort.setSuPath("/system/xbin/su");
                //默认su路径是/system/bin/su，有些设备su路径是/system/xbin/su
                //在new SerialPort();之前设置su路径
                serialPort = new SerialPort(new File("/dev/ttyS1"), 9600, 0);
            }catch (Exception e1){
                serialPort=null;
                return  null;
            }

        }
        return serialPort;
    }

    /**
     * 写入数据
     * @param hexString 16进制字符串
     */
    public    void  writeHexString(String hexString){
        OutputStream outputStream =null;
        try {
            outputStream.flush();
            //从串口对象中获取输出流
             outputStream = serialPort.getOutputStream();
            //写入数据
            outputStream.write(ByteUtil.hexStringToBytes(hexString));
            outputStream.flush();
        }catch (Exception e){
            //写入数据
            try {
                outputStream.flush();
            }catch (Exception e1){}
        }

    }



}
